<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/2/6
 * Time: 16:35
 */

namespace app\api\controller\v1;

use app\api\controller\Fun;
use app\api\repository\AddressRepository;
use app\api\service\BaiduMapService;
use app\api\service\FoundService;
use app\api\service\JpushService;
use app\api\service\ShaohuoOrderService;
use app\common\Model\Order;
use app\common\Model\OrderActionShaohuo;
use app\common\Model\OrderInfoShaohuo;
use app\common\Model\Region;
use app\common\Model\User;
use app\common\Model\UserAddress;
use think\Config;
use think\Db;
use think\exception\ErrorException;

/**
 * @title 捎货订单类接口V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class ShaohuoOrder extends Auth
{

    static public $validate = [
        'makeOrder' => [
            'base' => [
                'func_id' => 'func_id',
                'uid' => 'uid',
                'item_name' => 'item_name',
                'book_time' => 'book_time',
                'video_time' => 'video_time',
                'app_type' => 'app_type'
            ],
        ],
        'shippingFee' => [
            'base' => [
                'func_id' => 'func_id',
            ],
            'status' => [
                [
                    'key' => ['func_id'],
                    'value' => [
                        [
                            'rule' => [
                                'func_id' => 2,//帮送
                            ],
                            'valid' => [
                                'start_ua_id' => 'start_ua_id',
                            ]
                        ],
                        [
                            'rule' => [
                                'func_id' => 1,//帮买
                            ],
                            'valid' => [
                                'end_ua_id' => 'end_ua_id',
                            ]
                        ]
                    ]
                ]
            ]
        ],
        'cancelOrder' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
        'orderInfo' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
        'orderAction' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
        'completionOrder' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
        'shippingMap' => [
            'base' => [
                'order_id' => 'order_id',
            ]
        ],
    ];


    /**
     * @title 计算运费
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:shippingFee desc:计算运费
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:func_id type:string require:1 default: other: desc:功能id
     * @param name:start_ua_id type:string require:0 default: other: desc:发件地id,帮送业务
     * @param name:end_ua_id type:string require:0 default: other: desc:收件地id,帮买业务
     *
     * @return data:[]
     */
    public function shippingFee()
    {
        $ua_id = empty($this->arr['start_ua_id']) ?  $this->arr['end_ua_id'] : $this->arr['start_ua_id'];
        $fc_id = $this->arr['func_id'];

        $rtn = ShaohuoOrderService::instance()->shippingFee($fc_id,$ua_id);
        if($rtn){
            $shipping_fee = ShaohuoOrderService::$data['shipping_fee'];
            return Fun::success(['shipping_fee' => $shipping_fee]);
        }else{
            return Fun::error('');
        }
    }


    /**
     * @title 生成订单
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:makeOrder desc:生成订单
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:func_id type:string require:1 default: other: desc:功能id
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:item_name type:string require:1 default: other:名称
     * @param name:book_time type:int require:1 default: other:预约时间戳
     * @param name:video_time type:int require:1 default: other:录音秒数-1代表为汉字输入
     * @param name:app_type type:int require:1 default: other:订单来源1公众号2小程序3安卓4ios
     * @param name:serve_ua_id type:string require:0 default: other:服务地址id
     * @param name:start_ua_id type:string require:0 default: other:起始地址id
     * @param name:end_ua_id type:string require:0 default: other:结束地址id
     * @param name:remark type:string require:0 default: other:备注信息
     *
     * @return data:[]
     */
    public function makeOrder()
    {
        extract($this->arr);

        //获取控件字段配置
        $relation = Config::get('widget');

        //查询控件信息
        $widget_info = \app\common\Model\FuncClass::get(['fc_id' => $func_id]);
        $widget_model = new \app\common\Model\Widget();
        $widgets = $widget_model->where("w_id in ({$widget_info->widget_ids})")->select();

        $is_needpay = 1;
        $widget = [];
        foreach ($widgets as $item){
            $info['widget_name'] = $item->widget_name;
            $info['desc'] = $item->desc;

            //如果不需付款为待应答状态
            if($item->widget_name == 'publish'){
                $info_status = 2;
                $order_status = 5;
                $is_needpay = 0;
            }

            $widget[] = $info;
        }

        //捎货order表数据
        $data = [];
        //验证参数
        foreach ($widget as $item){
            if($arr = $relation[$item['widget_name']] ?? []){
                foreach ($arr as $key => $value){
                    if(!($$key ?? '') && ($value['is_null'] == 0)){
                        return Fun::error('999993',$key . '不存在');
                    }
                    $data[$key] = $$key ?? '';
                }
            }
        }

        $order_num = 'sh' . date('YmdHis') . rand(1000,9999);

        $book_time = date('Y-m-d H:i:s',strtotime($book_time));
        if($book_time < date('Y-m-d H:i')){
            return Fun::error('801028');
        }

        $data['fc_id'] = $func_id;
        $data['func_name'] = $widget_info->func_name;
        $data['uid'] = $uid;
        $data['book_time'] = $book_time;
        $data['status'] = $info_status ?? 1;
        $data['order_num'] = $order_num;
        $data['video_time'] = $video_time;
        $data['remark'] = $remark ?? '';
        $data['is_needpay'] = $is_needpay;

        $ua_id = ($data['start_ua_id'] ?? ($data['end_ua_id'] ?? null)) ?? $data['serve_ua_id'];

        //处理地址信息  根据地址id查询实际信息保存
        if($data['start_ua_id'] ?? 0){
            $start_addr = AddressRepository::instance()->orderAddress($data['start_ua_id']);
        }
        unset($data['start_ua_id']);
        $data['start_addr'] = json_encode($start_addr ?? []);
        if($data['end_ua_id'] ?? 0){
            $end_addr = AddressRepository::instance()->orderAddress($data['end_ua_id']);
        }
        unset($data['end_ua_id']);
        $data['end_addr'] = json_encode($end_addr ?? []);
        if($data['serve_ua_id'] ?? 0){
            $serve_addr = AddressRepository::instance()->orderAddress($data['serve_ua_id']);
        }
        unset($data['serve_ua_id']);
        $data['serve_addr'] = json_encode($serve_addr ?? []);

        //查询归属地id，优先取件地址，其次收件地址，再次服务地址
        $owner_addr = ($start_addr ?? ($end_addr ?? null)) ?? ($serve_addr ?? []);
        $region = Region::get(['name' => $owner_addr['district']]);
        $data['region_id'] = $region->region_id ?? 0;

        $distance = 0;
        //如果取件收件地址都存在计算距离
        if(!empty($start_addr) && !empty($end_addr)){
            $distance = BaiduMapService::instance()->getDistance($start_addr['lat'],$start_addr['lng'],
                $end_addr['lat'],$end_addr['lng']);
            $distance = $distance['distance'];
        }

        $data['distance'] = $distance;

        //计算运费
        $rtn = ShaohuoOrderService::instance()->shippingFee($func_id,$ua_id);
        if($rtn){
            $shipping_fee = ShaohuoOrderService::$data['shipping_fee'];
        }else{
            return Fun::error('');
        }
        $data['shipping_fee'] = $shipping_fee * 100;

        //基础order表数据
        $data_order = [
            'uid' => $uid,
            'type' => 1,
            'status' => $order_status ?? 1,
            'order_num' => $order_num,
            'app_type' => $app_type
        ];

        Db::startTrans();
        try{
            $rtn = Order::create($data_order);
            $data['order_id'] = $rtn->id;

            $order = OrderInfoShaohuo::create($data);
            $shipping_fee = sprintf("%.2f",$order->shipping_fee / 100);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($rtn->id,1,$uid);

            Db::commit();

            if($func_id != 1 && $func_id != 2){
                JpushService::instance()->makeOrder($rtn->id);
            }

            return Fun::success(['order_id' => $rtn->id,'shipping_fee' => $shipping_fee]);
        }catch (ErrorException $exception){
            Db::rollback();
            return Fun::error('');
        }
    }

    /**
     * @title 订单列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:OrderList desc:订单列表
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:func_id type:string require:0 default: other: desc:功能id
     * @param name:status type:string require:0 default: other:状态1待付款2待应答3待取件4待收件5待确认6或8已完成7已取消
     * @param name:current_page type:string require:0 default:1 other: desc:当前页
     * @param name:per_page type:string require:0 default:10 other: desc:每页大小
     *
     * @return data:[]
     */
    public function OrderList()
    {
        extract($this->arr);

        //组织查询条件
        $data['uid'] = $uid;
        if($func_id = $func_id ?? 0){
            $data['fc_id'] = $func_id;
        }

        $status = intval($status ?? 0);
        //6或8表示已完成订单
        if($status == 6 || $status == 8){
            $str = 'status = 6 or status = 8';
        }elseif($status == 0){
            $str = '1 = 1';
        }else{
            $str = 'status = '.$status;
        }

//        if($status = $status ?? 0){
//            $data['status'] = $status;
//        }

        $current_page = empty($current_page ?? 0) ? 1 : $current_page;
        $per_page = empty($per_page ?? 0) ? 10 : $per_page;
        //组织分页信息
        $paginate = [
            'page' => $current_page,
        ];

        //查询数据
        $info = OrderInfoShaohuo::where($data)
            ->where($str)
            ->order('id desc')->paginate(intval($per_page),false,$paginate)->toArray();

        //处理数据
        $list = [];
        foreach ($info['data'] as $item){
            $value = [];
            $value['start_user'] = '';
            $value['end_user'] = '';

            $value['order_id'] = $item['order_id'];
            $value['func_id'] = $item['fc_id'];
            $value['func_name'] = $item['func_name'];
            $value['order_num'] = $item['order_num'];
            $value['operate_time'] = $item['create_time'];
            $value['item_name'] = $item['item_name'];
            //如果是语音文件 拼接完整路径
//            if($item['video_time'] != -1){
//                $voice_url = Config::get('aliyun_oss.img_url');
//                $value['item_name'] = $voice_url . $value['item_name'];
//            }
            $value['shipping_fee'] = sprintf("%.2f",$item['shipping_fee'] / 100);
            $value['status'] = $item['status'];
            $value['video_time'] = $item['video_time'];

            //发件人收件人
            if($start_addr = json_decode($item['start_addr'])){
                $value['start_user'] = $start_addr->consignee ? $start_addr->consignee : $start_addr->mobile;
            }
            if($end_addr = json_decode($item['end_addr'])){
                $value['end_user'] = $end_addr->consignee ? $end_addr->consignee : $end_addr->mobile;
            }

            //最新路由信息
            $order_actions = OrderActionShaohuo::where(['order_id' => $item['order_id']])
                ->limit(1)->order('id desc')
                ->select();
            if($order_actions){
                $value['operate_time'] = $order_actions[0]->create_time;
                $order_action = $order_actions[0]->desc;
            }
            $value['order_action'] = $order_action ?? '';

            //捎货人手机号
            $value['shipping_user_mobile'] = User::get($item['shipping_uid'])->mobile ?? '';
            $list[] = $value;
        }

        $info['data'] = $list;

        return Fun::success($info);
    }

    /**
     * @title 取消订单
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:cancelOrder desc:取消订单
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function cancelOrder()
    {
        $order_id = $this->arr['order_id'];
        $uid = $this->arr['uid'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id,'uid' => $uid]);
        if(!$order_info){
            return Fun::error('801013');
        }

        //业务类型
        $func_id = $order_info->fc_id;

        if(empty($order_info)){
            return Fun::error('801013');
        }

        Db::startTrans();
        try{
            //待支付待应答允许取消
            if($order_info->status == 1){
                Order::where(['id' => $order_info->order_id])->update(['status' => 3]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7]);
            }elseif ($order_info->status == 2){
                //退款逻辑
                FoundService::instance()->drawBack($order_id);
                Order::where(['id' => $order_info->order_id])->update(['status' => 4]);
                OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 7]);
            }else{
                Db::rollback();
                //禁止取消
                return Fun::error('801011');
            }

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,3,$uid);

            Db::commit();
            return Fun::success([],'取消成功');
        }catch (ErrorException $exception){
            Db::rollback();
            //取消失败
            return Fun::error('801012');
        }
    }

    /**
     * @title 订单详情
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:orderInfo desc:订单详情
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function orderInfo()
    {
        $order_id = $this->arr['order_id'];
        $uid = $this->arr['uid'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id,'uid' => $uid]);
        if(empty($order_info)){
            return Fun::error('801013');
        }

        //返回数据
        $info = [];

        //订单总表信息
        $order = Order::get(['id' => $order_id,'uid' => $uid]);
        //支付方式
        $info['pay_type'] = $order['pay_type'];
        //订单来源
        $info['app_type'] = $order['app_type'];

        //名称
        $info['order_id'] = $order_id;
        $info['fc_id'] = $order_info['fc_id'];
        $info['func_name'] = $order_info['func_name'];
        $info['item_name'] = $order_info['item_name'];
        $info['video_time'] = $order_info['video_time'];
        $info['create_time'] = $order_info['create_time'];
        $info['book_time'] = $order_info['book_time'];
        $info['order_num'] = $order_info['order_num'];
        $info['status'] = $order_info['status'];
        $info['shipping_fee'] = strval($order_info['shipping_fee'] / 100);
        $info['remark'] = $order_info['remark'];
        //如果是语音文件 拼接完整路径
//        if($order_info['video_time'] != -1){
//            $voice_url = Config::get('aliyun_oss.img_url');
//            $info['item_name'] = $voice_url . $order_info['item_name'];
//        }

        $order_action = OrderActionShaohuo::all(['order_id' => $order_id]);

        $info['expected_time'] = '';//预计送达时间
        $info['complete_time'] = '';//订单完成时间
        $info['cancel_time'] = '';//订单取消时间
        $info['pay_time'] = '';//付款时间
        $info['takeorder_time'] = '';//接单时间
        $info['sendto_time'] = '';//送达时间
        $info['pickup_time'] = '';//取件时间

        //处理时间
        foreach ($order_action as $item){
            switch ($item->type)
            {
                case 1:
                    $info['create_time'] = $item->create_time;
                    break;
                case 2:
                    $info['pay_time'] = $item->create_time;
                    break;
                case 3:
                    $info['cancel_time'] = $item->create_time;
                    break;
                case 4:
                    $info['takeorder_time'] = $item->create_time;
                    break;
                case 5:
                    $info['pickup_time'] = $item->create_time;
                    break;
                case 6:
                    $info['sendto_time'] = $item->create_time;
                    break;
                case 7:
                    $info['complete_time'] = $item->create_time;
            }
        }

        //用户信息
        $user_info = User::get($uid);
        $info['user_name'] = $user_info['real_name'] ? $user_info['real_name'] : $user_info['nick_name'];
        $info['user_phone'] = $user_info['mobile'];

        //发件人
        $start_addr = json_decode($order_info->start_addr,true);
        if($start_addr){
            $info['addr'][] = $start_addr ? array_merge($start_addr,['type' => 'start_addr']) : [];
        }

        //收件人
        $end_addr = json_decode($order_info->end_addr,true);
        if($end_addr){
            $info['addr'][] = $end_addr ?  array_merge($end_addr,['type' => 'end_addr']) : [];
        }

        //发布人
        $serve_addr = json_decode($order_info->serve_addr,true);
        if($serve_addr){
            $info['addr'][] = $serve_addr ? array_merge($serve_addr,['type' => 'serve_addr']) : [];
        }

        //如果是帮送且为待收件待确认状态 查询当前捎货人地址
        if($order_info->fc_id == 2 && ($order_info->status == 4 || $order_info->status == 5)){
            $shipping_user = ShaohuoOrderService::instance()->orderMap($order_id);
        }
        $info['shipping_user'] = $shipping_user ?? (object)[];
        $info['remaining_time'] = strval($shipping_user['remaining_time'] ?? 0);//剩余配送时间

        $info['distance'] = strval($order_info['distance'] ?? '');

        //预约时间描述
        $info['book_time_desc'] = '预约时间';
        switch ($order_info['fc_id']){
            case 1:
                $info['book_time_desc'] = '预约送达时间';
                break;
            case 2:
                $info['book_time_desc'] = '预约取件时间';
                break;
            default:
                $info['book_time_desc'] = '预约服务时间';
        }

        //路由信息
        $routes = OrderActionShaohuo::where(['order_id' => $order_id])->select();
        foreach ($routes as $item){
            if($item->type == 3){
                $info['cancel_time'] = $item->create_time;
            }
            if($item->type == 7){
                $info['complete_time'] = $item->create_time;
            }
        }

        return Fun::success($info);
    }

    /**
     * @title 订单路由信息
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:orderAction desc:订单路由信息
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function orderAction()
    {
        $order_id = $this->arr['order_id'];
        $uid = $this->arr['uid'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id,'uid' => $uid]);
        if(empty($order_info)){
            return Fun::error('801013');
        }

        $data['order_num'] = $order_info['order_num'];
        $data['status'] = $order_info['status'];
        $shipping_user = $order_info['shipping_uid'] ? User::get($order_info['shipping_uid']) : null;
        $data['shipping_user_mobile'] = $shipping_user->mobile ?? '';
        $data['shipping_user_name'] = $shipping_user->name ?? '';

        $list = OrderActionShaohuo::where(['order_id' => $order_id])->order('id desc')->select();
        if($list){
            foreach ($list as &$item){
                $item = $item->toArray();
                unset($item['commit']);
                unset($item['update_time']);
                unset($item['deal_uid']);

            }
            $data['list'] = $list;
            return Fun::success($data);
        }else{
            return Fun::error('801014');
        }


    }

    /**
     * @title 确认签收订单
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:completionOrder desc:确认签收订单
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function completionOrder()
    {
        $uid = $this->arr['uid'];
        $order_id = $this->arr['order_id'];
        //查询订单信息
        $order_info = OrderInfoShaohuo::get(['order_id' => $order_id,'uid' => $uid]);
        if(empty($order_info)){
            return Fun::error('801013');
        }
        //业务类型
        $func_id = $order_info->fc_id;
        Db::startTrans();
        try{
            //修改订单总表及捎货订单表信息
            Order::where(['id' => $order_info->order_id])->update(['status' => 5]);
            OrderInfoShaohuo::where(['order_id' => $order_info->order_id])->update(['status' => 6]);

            //添加路由信息
            ShaohuoOrderService::instance()->orderAction($order_id,7,$uid);
            Db::commit();
            return Fun::success([],'确认订单成功');
        }catch (ErrorException $exception){
            Db::rollback();
            //todo 操作失败 定义错误码
            return Fun::error('');
        }
    }

    /**
     * @title 刷新配送员地址
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:ShaohuoOrder desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:shippingMap desc:刷新配送员地址
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other:用户id
     * @param name:order_id type:string require:1 default: other: desc:订单id
     *
     * @return data:[]
     */
    public function shippingMap()
    {
        $order_id = $this->arr['order_id'];
        $info = ShaohuoOrderService::instance()->orderMap($order_id);
        return Fun::success($info,'刷新成功');
    }
}